/*
 * Copyright (c) 2010 Scott Morgan
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package captaintest;

import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;

import java.io.*;
import java.util.*;

public class HtmlReportGenerator {
    private List<FileCoverage> fileCoverages;
    private String coverageType;
    private OutputStream outputStream;
    private boolean isFile;

    public HtmlReportGenerator(List<FileCoverage> fileCoverages, String coverageType, OutputStream outputStream) {
        this.fileCoverages = fileCoverages;
        this.coverageType = coverageType;
        this.outputStream = outputStream;
    }

    public HtmlReportGenerator(List<FileCoverage> fileCoverages, String coverageType, File outputFile) throws FileNotFoundException {
        this.fileCoverages = fileCoverages;
        this.coverageType = coverageType;
        this.outputStream = new FileOutputStream(outputFile);
        this.isFile = true;
    }

    public void generate() {
        try {
            Configuration cfg = new Configuration();
            cfg.setClassForTemplateLoading(HtmlReportGenerator.class, "");

            cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);

            Template tpl = cfg.getTemplate("htmlreport.ftl");
            OutputStreamWriter output = new OutputStreamWriter(outputStream);

            Map root = new HashMap();

            List<FileCoverage> copy = new ArrayList<FileCoverage>(fileCoverages.size());
            for (FileCoverage fc : fileCoverages) {
                if (fc.hasError(coverageType)){
                    copy.add(fc);
                }
            }
            Collections.sort(copy);

            root.put("list", copy);
            if (coverageType == null){
                coverageType = "any"; // freemarker doesn't like null
            }
            root.put("type", coverageType);

            tpl.process(root, output);


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (isFile){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }

    }
}

